package com.windward.vii.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.windward.vii.common.JsonResult;
import com.windward.vii.common.ResultCode;
import com.windward.vii.config.TupuConfig;
import com.windward.vii.dao.entity.UserContent;
import com.windward.vii.dao.mapper.UserContentMapper;
import com.windward.vii.domain.ugc.UserContentVO;
import com.windward.vii.utils.StringUtils;
import com.windward.vii.utils.ThreadPoolManager;
import com.windward.vii.service.tupu.TupuApi;
import com.windward.vii.service.tupu.model.ImageResult;
import com.windward.vii.service.tupu.model.Options;
import com.windward.vii.service.tupu.model.YellowResult;
import com.windward.vii.service.tupu.util.ConfigUtil;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class UserContentService {

    private static Logger logger = LoggerFactory.getLogger(UserContentService.class);

    @Resource
    UserContentMapper userContentMapper;
    @Resource
    TupuConfig tupuConfig;

    public JsonResult insert(UserContent userContent) {
        if(StringUtils.isBlank(userContent.getImages())) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "请选择图片");
        }
        userContent.setCreateTime(new Date());
        userContent.setUpdateTime(new Date());
        logger.info("insert: images={}", userContent.getImages());
        int row = userContentMapper.insertSelective(userContent);
        if(row > 0) {
            asyncYellowCheck(userContent.getId(), userContent.getImages());
        }
        return row > 0 ? JsonResult.success() : JsonResult.error();
    }

    private void asyncYellowCheck(final Long id, final String images) {
        ThreadPoolManager.getInstance().addExecuteTask(new Runnable() {
            @Override
            public void run() {
                logger.info("asyncYellowCheck: begin {}----------------------", System.currentTimeMillis());
                logger.info("asyncYellowCheck: id={}, images={}", id, images);
                // secret id
                String secretId = tupuConfig.getSecretId();
                // private KEY path
                String privateKeyPath = tupuConfig.getPrivateKeyPath();
                // request Url
                String requestUrl = "http://api.open.tuputech.com/v3/recognition/";
                // fileList imageFile or url
//                ArrayList<String> fileLists = new ArrayList<String>();
//                fileLists.add("../test1.jpg");
//                fileLists.add("../test2.jpg");

                String stylename = "/256h_256w";
                List<String> imageList = JSON.parseArray(images, String.class);
                ArrayList<String> fileLists = new ArrayList<>();
                for(String url : imageList) {
                    fileLists.add(url + stylename);
                }

                // tags
                String tags[] = {String.valueOf(id)};
                // options
                Options options = new Options();
                options.setTags(tags);
                // options.setUid("your_uid"); // 第三方客户标识

                TupuApi tupuApi = new TupuApi(secretId, privateKeyPath, requestUrl);
                JSONObject result = tupuApi.doApiTest(ConfigUtil.UPLOAD_TYPE.UPLOAD_URI_TYPE, fileLists, options);
                logger.info("asyncYellowCheck: result={}", result.toString());
                if(result.getInt("code") == 0) {
                    JSONObject jsonObject = result.getJSONObject(tupuConfig.getTaskId());
                    if(jsonObject != null) {
                        YellowResult yellowResult = JSON.parseObject(jsonObject.toString(), YellowResult.class);
                        if(yellowResult != null) {
                            List<ImageResult> list = yellowResult.getFileList();
                            List<String> legalImages = new ArrayList<>();   // 合法图片
                            if(list != null && list.size() > 0) {
                                for(ImageResult imageResult : list) {
                                    if(imageResult.getLabel() == 2) {
                                        legalImages.add(imageResult.getName().replace(stylename, ""));
                                    }
                                }
                            }
                            int illegalNum = 0;
                            try {
                                if(yellowResult.getStatistic() != null) {
                                    illegalNum = Integer.parseInt(yellowResult.getStatistic()[0]);
                                }
                            } catch (Exception e) {
                                if(yellowResult.getStatistic() != null) {
                                    logger.info("asyncYellowCheck: result.statistic={}", yellowResult.getStatistic());
                                } else {
                                    logger.info("asyncYellowCheck: result.statistic is null");
                                }
                            }

                            boolean isExistIllegal = illegalNum > 0;
                            logger.info("asyncYellowCheck: isExistIllegal={}, num={}", isExistIllegal, illegalNum);
                            // 更新鉴黄结果
                            UserContent userContent = new UserContent();
                            userContent.setId(id);
                            userContent.setImages(JSON.toJSONString(legalImages));
                            userContent.setUpdateTime(new Date());
                            userContent.setIsReview(true);
                            userContent.setReviewResult(jsonObject.toString());
                            userContent.setIsExistIllegal(isExistIllegal);
                            update(userContent);
                        }
                    }
                }
                logger.info("asyncYellowCheck: end {}----------------------", System.currentTimeMillis());
            }
        });
    }

    public JsonResult update(UserContent userContent) {
        if(userContent.getId() == null) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "更新ID不能为空");
        }
        if(StringUtils.isBlank(userContent.getImages())) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "请选择图片");
        }
        userContent.setUpdateTime(new Date());
        int row = userContentMapper.updateByPrimaryKeySelective(userContent);
        logger.info("update is success ? {}", row > 0);
        return row > 0 ? JsonResult.success() : JsonResult.error();
    }

    public JsonResult delete(Long id) {
        int row = userContentMapper.deleteByPrimaryKey(id);
        return row > 0 ? JsonResult.success() : JsonResult.error("删除失败或不存在该动态");
    }

    public JsonResult getContentListByUid(Long uid, Integer pageNum, Integer pageSize) {
        if(uid == null || uid <= 0) {
            return new JsonResult(ResultCode.PARAM_ERROR_CODE, "用户ID错误");
        }
        pageNum = pageNum == null ? 1 : pageNum;
        pageSize = pageSize == null ? 10 : pageSize;
        PageHelper.startPage(pageNum, pageSize);
        List<UserContent> list = userContentMapper.getContentListByUid(uid);

        List<UserContentVO> destList = new ArrayList<>();
        if (list != null && list.size() > 0) {
            try {
                for (UserContent userContent : list) {
                    String images = userContent.getImages();
                    JSONArray array = JSON.parseArray(images);
                    if(array != null && array.size() > 0) {
                        UserContentVO userContentVO = new UserContentVO();
                        BeanUtils.copyProperties(userContentVO, userContent);
                        destList.add(userContentVO);
                    }
                }
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }

        JsonResult jsonResult = JsonResult.success();
        jsonResult.setBody(destList);
        return jsonResult;
    }

}
